package com.beamfield.controller.manage.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.beamfield.controller.common.BaseController;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.*;
import com.beamfield.modelVo.AdminInfoVo;
import com.beamfield.modelVo.BtnDto;
import com.beamfield.modelVo.ModelDto;
import com.beamfield.service.manage.auth.AdminInfoService;
import com.beamfield.service.manage.auth.PermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.beamfield.common.ApiResult;
import com.beamfield.common.CommonUtils;
import com.beamfield.common.PageResult;
import com.beamfield.service.manage.sys.DictonaryService;
import com.beamfield.service.manage.sys.FileService;
import com.beamfield.service.manage.auth.RoleInfoService;

/**
 * 权限部分
 * @author zhaohh
 *
 */
@Controller
@RequestMapping("/cms/role")
public class RoleInfoController extends BaseController {

	@Value("${session.user}")
	private String sessionUser;

	@Value("${session.beam}")
	private String beam;

	@Resource
	RoleInfoService roleInfoService;

	@Autowired
    private PermissionService permissionService;

	@Autowired
    private AdminInfoService adminInfoService;

	@Resource
	FileService fileService;

	@Resource
	DictonaryService dictonaryService;

	/**
	 * 部门管理页面
	 * @return
	 */
	@RequestMapping("/admindp")
	public ModelAndView admindp(){
		return new ModelAndView();
	}

	/**
	 * 权限编辑
	 * @return
	 */
	@RequestMapping("/permission")
	public ModelAndView permission(){
		return new ModelAndView();
	}

	/**
	 * 公司管理页面
	 * @return
	 */
	@RequestMapping("/company")
	public ModelAndView company(){
		return new ModelAndView();
	}

	/**
	 * 公司管理编辑页面
	 * @return
	 */
	@RequestMapping("/editCompany")
	public ModelAndView editCompany(){
		return new ModelAndView();
	}

    /**
     * 公司用户管理
     * @return
     */
	@RequestMapping(value = "/company_user")
	public ModelAndView companyUser(){
	    return new ModelAndView();
    }

	/**
	 * 一级部门的查询  查二级时，先查出符合条件的所属的一级，然后再点击下拉展开查询二级
	 * @param offset
	 * @param limit
	 * @param name
	 * @param type
	 * @param level
	 * @param session
	 * @return
	 */
	@RequestMapping("/getFirstDpList")
	@ResponseBody
	public PageResult getFirstDpList(Integer offset, Integer limit,String name,Integer type,Integer level,HttpSession session){
		Long beam_id = (Long) session.getAttribute(beam);
		return roleInfoService.getFirstDpList( offset,  limit, name, type,level,beam_id);
	}

	/**
	 * 二级部门的查询
	 * @param offset
	 * @param limit
	 * @param name
	 * @param type
	 * @param level
	 * @param session
	 * @return
	 */
	@RequestMapping("/getSecondDpList")
	@ResponseBody
	public PageResult getSecondDpList(Integer offset, Integer limit,String name,Integer type,Integer fdpid,HttpSession session){
		Long beam_id = (Long) session.getAttribute(beam);
		return roleInfoService.getSecondDpList( offset,  limit, name, type,fdpid,beam_id);
	}

	@RequestMapping("/getBeamList")
	@ResponseBody
	public PageResult getBeamList(Long dpId){
		return roleInfoService.getBeamList(dpId);
	}

	/**
	 * 删除部门
	 * @param id
	 * @param session
	 * @return
	 */
	@RequestMapping("/delAmindp")
	@ResponseBody
	public ApiResult delAmindp(Long id,HttpSession session){
		Long user = (Long) session.getAttribute(sessionUser);
		return roleInfoService.delAmindp( id,user);
	}

	/**
	 * 编辑部门页面
	 * @return
	 */
	@RequestMapping("/editAdmindp")
	public ModelAndView editAdmindp(){
		return new ModelAndView();
	}

	/**
	 * 获取部门数据
	 * @param id
	 * @param session
	 * @return
	 */
	@RequestMapping("/getAdmindpInfo")
	@ResponseBody
	public ApiResult getAdmindpInfo(Long id,int type,HttpSession session){
		ApiResult apiResult = new ApiResult();
		Map<String, Object> map = new HashMap<>();
		Long beam_id = (Long) session.getAttribute(beam);

		//父级部门的数据
		List<AdminDp> list = roleInfoService.getFadmindpInfo(beam_id,type);
		//部门的数据
		AdminDp adminDp = roleInfoService.getAdminDpInfo(id);
		map.put("list", list);
		map.put("adminDp", adminDp);
		apiResult.setResult(map);
		return apiResult;
	}

	/**
	 * 修改/新增部门数据
	 * @param id
	 * @param session
	 * @return
	 */
	@RequestMapping("/doEditAdmindp")
	@ResponseBody
	public ApiResult doEditAdmindp(AdminDp adminDp,HttpSession session){
		Long beam_id = (Long) session.getAttribute(beam);
		Long user = (Long) session.getAttribute(sessionUser);
		return roleInfoService.doEditAdmindp(adminDp,beam_id,user);
	}

	/**
	 * 修改/新增部门数据
	 * @param id
	 * @param session
	 * @return
	 */
	@RequestMapping("/doEditAdmindp2")
	@ResponseBody
	public ApiResult doEditAdmindp2(String formJson,HttpSession session){
		if(StringUtils.isEmpty(formJson)){
			return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
		}
		Long beam_id = (Long) session.getAttribute(beam);
		Long user = (Long) session.getAttribute(sessionUser);
		try{
            AdminDp adminDp = JSON.parseObject(formJson, AdminDp.class);
            return roleInfoService.doEditAdmindp(adminDp,beam_id,user);
        }catch (Exception e){
			e.printStackTrace();
		}
		return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
	}

	/**
	 * 获取部门树
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getDepartmentTree", method = RequestMethod.GET)
	@ResponseBody
	public ApiResult getDepartmentTree(HttpServletRequest request){
        Long beamId = super.getBeamId(request);
        String type = request.getParameter("type");
        try {
            return this.permissionService.getDepartmentTree(beamId, type);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 根据部门获取角色信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/getRoleIno", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getRoleIno(HttpServletRequest request){
        String dpId = request.getParameter("dp_id");
        if(StringUtils.isEmpty(dpId)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        try {
            return this.permissionService.getRoleIno(dpId);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 根据角色获取模块信息树
     * @param request
     * @return
     */
    @RequestMapping(value = "/getModelTree", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getModelTree(HttpServletRequest request){
        String roleId = request.getParameter("roleId");
        //类型 总公司、梁场
        String type = request.getParameter("type");
        //平台
        String platform = request.getParameter("platform");
        if(StringUtils.isEmpty(roleId)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        try {
            return this.permissionService.getModelTree(platform, roleId, type);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 根据角色id和模块id获取按钮
     * @param request
     * @return
     */
    @RequestMapping(value = "/getBtnByRoleAndModelId", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getBtnByRoleAndModelId(HttpServletRequest request){
        String roleId = request.getParameter("roleId");
        String modelId = request.getParameter("modelId");
        if(StringUtils.isEmpty(roleId) || StringUtils.isEmpty(modelId)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        try {
            return this.permissionService.getBtnByRoleAndModelId(roleId, modelId);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

	/**
	 * 保存按钮信息
	 * @param request
	 * @param btn
	 * @return
	 */
	@RequestMapping(value = "/doSaveBtn", method = RequestMethod.POST)
	@ResponseBody
    public ApiResult doSaveBtn(HttpServletRequest request, Btn btn){
        Long beamId = super.getBeamId(request);
        try {
            return permissionService.saveBtn(beamId, btn);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 保存权限
     * @param request
     * @return
     */
    @RequestMapping(value = "/doSaveBtnPermission", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult doSaveBtnPermission(HttpServletRequest request, @RequestParam("role_id") String roleId,
                                      @RequestParam("btnDtoJson") String btnDtoJson){
	    if(StringUtils.isEmpty(roleId) || StringUtils.isEmpty(btnDtoJson)){
	        return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        Long beamId = super.getBeamId(request);
	    try{
            List<BtnDto> btnDtoList = JSON.parseArray(btnDtoJson, BtnDto.class);
            return permissionService.saveBtnPermission(beamId, roleId, btnDtoList);
        }catch (Exception e){
	        e.printStackTrace();
	        return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 保存模块权限
     * @param request
     * @return
     */
    @RequestMapping(value = "/doSaveModelPermission", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult doSaveModelPermission(HttpServletRequest request, @RequestParam("roleId") String roleId,
                                           @RequestParam("modelsJson") String modelsJson){
        if(StringUtils.isEmpty(roleId) || StringUtils.isEmpty(modelsJson)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        try{
            List<ModelDto> modelDtoList = JSON.parseArray(modelsJson, ModelDto.class);
            return this.permissionService.saveModelPermission(Long.parseLong(roleId), modelDtoList);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

	/**
	 * 保存角色
	 * @param request
	 * @param dpId
	 * @param roleName
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "/doSaveRoleInfo", method = RequestMethod.POST)
	@ResponseBody
	public ApiResult doSaveRoleInfo(HttpServletRequest request, @RequestParam("dpId") String dpId,
									@RequestParam("roleName") String roleName,
									@RequestParam("roleId") String roleId,
                                    @RequestParam("type") String type){
		if(StringUtils.isEmpty(dpId) || StringUtils.isEmpty(roleName)){
			return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
		}
        Long beamId = super.getBeamId(request);
        try{
			return this.permissionService.saveRoleInfo(dpId, roleName, roleId, beamId, type);
		}catch (Exception e){
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
		}
	}

	/**
	 * 删除角色
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/delRole", method = RequestMethod.POST)
	@ResponseBody
	public ApiResult delRole(HttpServletRequest request, @RequestParam("id") String id){
		if(StringUtils.isEmpty(id)){
			return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
		}
		try{

			return this.permissionService.delRole(id);
		}catch (Exception e){
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
		}
	}

    /**
     * 获取公司用户
     * @param request
     * @return
     */
	@RequestMapping(value = "/readCompanyUserData", method = RequestMethod.GET)
    @ResponseBody
	public PageResult readCompanyUserData(HttpServletRequest request){
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        String name = request.getParameter("name");
        List<AdminInfoVo> adminInfoVoList = permissionService.getCompanyUserData(offset, limit, name);
        long total = permissionService.countCompanyUserData(name);
        return new PageResult(total, Long.parseLong(offset), adminInfoVoList);
    }

    /**
     * 保存公司用户
     * @param request
     * @param adminInfoFormJson
     * @return
     */
    @RequestMapping(value = "/doSaveCompanyUser", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult doSaveCompanyUser(HttpServletRequest request, String adminInfoFormJson){
        if(StringUtils.isEmpty(adminInfoFormJson)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        Long userId = super.getUserId(request);
        try{
            AdminInfo adminInfo = JSON.parseObject(adminInfoFormJson, AdminInfo.class);
            if(adminInfo.getRole_id() == null){
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), "请选择角色");
            }
            if(StringUtils.isEmpty(adminInfo.getPwd_eight())){
                adminInfo.setPwd_eight("123456");
            }
            adminInfo.setOperator(userId);
            return adminInfoService.save(adminInfo);
        }catch (Exception e){
	        e.printStackTrace();
        }
        return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
    }

	/**
	 * 删除公司用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/doDelCompanyUser", method = RequestMethod.POST)
	@ResponseBody
    public ApiResult doDelCompanyUser(Long id){
		return adminInfoService.doDelCompanyUser(id);
	}
}
